<template>
  <div class="app-container">
<!--    用量对比页面-->
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div class="treeCont" style="max-height:96%; height: 96%; overflow-y: auto;margin-top: 10px;">
            <el-tree
                :data="sheetsTreeList"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                node-key="sheetsCode"
                :default-expanded-keys="defaultExpandedKeys"
                highlight-current
                v-loading="treeLoading"
                @node-click="handleNodeClick"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node"
                     style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <!--                <div style="vertical-align: -0.15em;margin-right: 5px; display: block;">-->
                  <!--                                   <el-icon-folder-checked  style="height: 1.1em;width: 1.1em" />-->
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                  <!--                <i class="el-icon-menu" v-if="data.deviceType == 1" ></i>-->
                  <!--                <i class="el-icon-s-grid" v-if="data.deviceType == 2" ></i>-->
                  <!--                </div>-->
                  <span>{{ node.label }}</span>
                  <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <!--户表用量突增突减数据-->
      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <div style="width: 100%;margin: 10px 5px 10px 0;">
          <el-row class="line-bottom" v-show="showSearch">
            <el-col class="form_col">
              <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch" :rules="queryrules"
                       :label-width="labelWidth">
                <div id="searchFilter" style="display: flex;justify-content: start; flex-wrap: wrap;">
                  <el-form-item label="用户编号" prop="userId">
                    <el-input :size="formItemSize"
                              style="width: 100%;"
                              v-model="queryParams.userId"
                              placeholder="输入输入用户编号"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                  <el-form-item label="目标月份" prop="nowMonth">
                    <el-date-picker :size="formItemSize"
                                    style="width: 100%;"
                                    v-model="queryParams.nowMonth"
                                    placeholder="选择日期"
                                    :clearable="false"
                                    type="month"
                                    value-format="yyyy-MM"/>
                  </el-form-item>
                  <el-form-item label="对比月份" prop="comparisonMonth">
                    <el-date-picker :size="formItemSize"
                                    style="width: 100%;"
                                    v-model="queryParams.comparisonMonth"
                                    placeholder="选择日期"
                                    :clearable="false"
                                    type="month"
                                    value-format="yyyy-MM"/>
                  </el-form-item>
                  <el-form-item label="用量增减比率" prop="comparisonRate" label-width="100px">
                    <el-input placeholder="如：50" v-model="queryParams.comparisonRate" size="mini"
                    >
                      <el-select :size="formItemSize" v-model="queryParams.symbol" slot="prepend" placeholder="请选择" style="width: 100px"
                      >
                        <el-option v-for="(item,index) in selectlist" :key="index" :label="item.name"
                                   :value="item.key">{{ item.name }}
                        </el-option>
                      </el-select>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="用户名称" prop="userName">
                    <el-input :size="formItemSize"
                              v-model="queryParams.userName"
                              placeholder="输入区域名称"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                  <el-form-item label="设备编号" prop="terminalId">
                    <el-input :size="formItemSize"
                              v-model="queryParams.terminalId"
                              placeholder="输入设备编号"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                  <el-form-item label="表解析地址" prop="communicateAddress">
                    <el-input :size="formItemSize"
                              v-model="queryParams.communicateAddress"
                              placeholder="输入表解析地址"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                </div>
              </el-form>
            </el-col>

            <el-col class="form_query">
              <el-button v-show="collapseAble" type="text" size="mini" @click="shiftCollapseAble" class="text">
                    <span>
                      {{ fold ? '收起筛选' : '更多筛选' }}
                    </span>
              </el-button>
              <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
              <el-button @click="resetQuery" size="mini">重置</el-button>
              <RightDropdown :columns="columns" :showSearch.sync="showSearch" :queryVisible="false" @queryTable="getList" @export="handleExport"
                             :hasPermiExport="['dataananysis:areadosage:export']" style="margin-left: 10px"></RightDropdown>
            </el-col>
          </el-row>
          <el-row>
            <el-table ref="table" v-loading="loading" :data="dataList" border size="mini"
                      :default-sort="defaultSort" @sort-change="handleSorterChange" :height="getAvailableHeight">
              <el-table-column v-for="(item,index) in columns" :key="index" :prop="item.dataIndex" align="center"
                               :label="item.label" :sortable="item.sortable" :sort-orders="item.sortOrders"
                               :show-overflow-tooltip="true" v-if="item.visible" :width="item.width">
              </el-table-column>
            </el-table>
            <pagination
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import moment from 'moment'
import {getDosageList} from "@/api/datastatistics/meterread/dosagestatics.js"
import {listMeterSheetsTree} from "@/api/basedata/meterSheets";
import {deepCopy} from '@/utils/ruoyi'
import { getAreaTree } from "@/api/tree/index"

export default {
  name: "DosageStaticsXb",
  data() {
    return {
      defaultExpandedKeys: [],
      screenHeight: null,
      // 列信息
      columns: [
        {
          key: 0,
          label: `区域名称`,
          visible: true,
          dataIndex: 'sheetsName',
          sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 1,
          label: `用户编号`,
          visible: true,
          dataIndex: 'userId',
          sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 2,
          label: `用户名称`,
          visible: true,
          dataIndex: 'userName',
          sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        // {
        //   key: 3,
        //   label: `安装地址`,
        //   visible: true,
        //   dataIndex: 'installAddress',
        //   sortable: 'custom',
        //   sortOrders: ['ascending', 'descending']
        // },
        {
          key: 4,
          label: `设备编号`,
          visible: true,
          dataIndex: 'terminalId',
          sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 5,
          label: `表解析地址`,
          visible: true,
          dataIndex: 'communicateAddress',
          sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 6,
          label: `目标月份`,
          visible: true,
          dataIndex: 'nowMonth',
          sortable: false,
        },
        {
          key: 7,
          label: `目标用量(m³)`,
          visible: true,
          dataIndex: 'nowDosage',
          width: 130,
          sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 8,
          label: `对比月份`,
          visible: true,
          dataIndex: 'comparisonMonth',
          sortable: false,
        },
        {
          key: 9,
          label: `对比用量(m³)`,
          visible: true,
          dataIndex: 'comparisonDosage',
          width: 130,
          sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
        {
          key: 10,
          label: `用量增减比率(%)`,
          visible: true,
          dataIndex: 'rate',
          width: 150,
          sortable: 'custom',
          sortOrders: ['ascending', 'descending']
        },
      ],
      // 默认排序
      defaultSort: {prop: 'rate', order: 'descending'},
      // 表单校验
      queryrules: {
        nowMonth: [
          {required: true, message: "对比月份不能为空", trigger: "blur"}
        ],
        comparisonMonth: [
          {required: true, message: "当前月份不能为空", trigger: "blur"}
        ],
      },
      collapseAble: false,
      fold: false,
      formItemSize: 'mini',
      labelWidth: '90px',
      maxShow: 4,
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      // 表格数据
      dataList: [],
      // 表格数据拷贝
      copyTableDataList: [],
      // 区域树选项
      sheetsTreeList: [],
      // 区域名称
      keyWordName: undefined,
      // 树状态
      treeVisibale: true,
      // 遮罩层
      treeLoading: true,
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: null,
        nowMonth: moment().subtract(1, 'month').format('YYYY-MM'),
        comparisonMonth: moment().subtract(2, 'month').format('YYYY-MM'),
        userId: null,
        comparisonRate: null,
        symbol: 1,
        userName: null,
        terminalId: null,
        communicateAddress: null,
        systemFlag: null,
        loginUserId: null,
      },
      // 总条数
      total: 0,
      showtime: true,
      selectlist: [{key: 1, name: '大于等于'}, {key: 2, name: '小于等于'}, {key: 3, name: '等于'}],
      filterText: ''
    };
  },
  created() {
    this.screenHeight = document.body.clientHeight
    this.tip()
    this.getTreeList();
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? (this.fold ? 250 : 211) : 165)
    },
    userId() {
      return this.$store.state.user.userId
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    }
  },
  mounted() {
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = this.defaultSort.prop
        this.queryParams.isAsc = this.defaultSort.order
      }
    },
    init() {
      // 调用接口获取到数据后
      let _self = this
      this.$nextTick(() => {
        window.setTimeout(() => {
          _self.$refs.table.doLayout()
        }, 100)
      })
    },
    handleNodeClick(data){
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          let choiceCheck = this.$refs.tree.getCurrentNode()
          if (choiceCheck) {
            this.queryParams.sheetsCode = choiceCheck.sheetsCode
            this.queryParams.systemFlag = this.systemFlag
            this.queryParams.loginUserId = this.userId
            this.queryParams.pageNum = 1;
            this.getList()
          } else {
            this.dataList = []
            this.copyTableDataList = []
            this.total = 0
            this.$modal.msgWarning("请选择一个区域!")
          }
        }
      })
    },
    // 重置表单
    resetQuery() {
      this.$refs.tree.setCurrentKey(null)
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: null,
        nowMonth: moment().subtract(1, 'month').format('YYYY-MM'),
        comparisonMonth: moment().subtract(2, 'month').format('YYYY-MM'),
        userId: null,
        comparisonRate: null,
        symbol: 1,
        sheetsName: null,
        terminalId: null,
        communicateAddress: null,
        systemFlag: null,
        loginUserId: null,
      }
      this.dataList = []
      this.copyTableDataList = []
      this.handleQuery();
    },
    // 获取表格数据
    getList() {
      if(this.queryParams.sheetsCode === null){
        return this.$message.warning('请选择一个区域查看数据!')
      }
      this.checkSortColumn()
      this.loading = true;
      getDosageList(this.queryParams).then(response => {
        if (response.code === 200) {
          this.dataList = response.rows
          this.copyTableDataList = response.rows
          this.init()
          this.loading = false;
          this.total = response.total
        } else {
          this.$modal.msgError("数据查看失败!")
          this.loading = false;
        }
      });
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      // let treeType = "0,1"
      // getAreaTree(treeType).then(response => {
      //   this.sheetsTreeList = response.data;
      //   this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
      //   this.treeLoading = false;
      // });
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if (this.sheetsTreeList.length === 0){
        this.treeLoading = false;
      }else{
        this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
        this.treeLoading = false;
      }
    },
    // 改变tree的显示与隐藏
    changeTreeShow() {
      this.treeVisibale = !this.treeVisibale
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datastatistics/terminalXbStatisticAnalysis/dosageUprushExport', {
        ...this.queryParams
      }, `户表用量突增减统计数据.xlsx`)
    },
    //自定义表格排序
    /**
     * 思路：
     * 先过滤掉'-'和null
     * 对新数组进行常规升/降序排序，根据传入的order判断是升序还是降序
     * 如果点击表头取消排序也需要做判断，将数据还原成接口返回的数据
     */
    handleSort({column, prop, order}) {
      // sortable 的值需要设置为'custom'
      //prop：排序的字段、order：升序（ascending）、降序（descending）、取消排序（null）
      let copyTableDate = deepCopy(this.dataList);   //拷贝表格数据
      let reserveData = [];                          //过滤后保留的数据
      let filterData = [];                          //过滤掉的数据
      //开始进行数据过滤：将'--'过滤到filterData数组中，剩余数值型数据保留到reserveData中。
      copyTableDate.forEach(item => {
        if (item[prop] === '-' || item[prop] === null) {    //item[prop]：将要排序那个字段的值
          filterData.push(item);    //item：表格中的这条数据，即row
        } else {
          reserveData.push(item);
        }
      });
      // 排序
      if (order !== null) {
        if (order === 'descending') {   //降序
          // 冒泡排序
          reserveData = reserveData.sort((a, b) => parseFloat(b[prop]) - parseFloat(a[prop]));
        } else { //升序
          reserveData = reserveData.sort((a, b) => parseFloat(a[prop]) - parseFloat(b[prop]));
        }
        // 过滤掉的数据添加到数组末尾
        filterData.forEach(item => {
          reserveData.push(item);
        });
        this.dataList = reserveData;
        this.$forceUpdate()
        this.$refs.table.doLayout()
      } else {
        // 取消排序
        //this.copyTable是在接口得到表格数据的时候拷贝了一份，用来还原取消排序时的表格数据
        this.dataList = this.copyTableDataList;
      }
    },
    // 页面提示信息
    tip() {
      this.$modal.msgWarning("请选择一个区域查看数据!")
      this.loading = false;
    },
  }
};
</script>
<style scoped lang="scss">
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node{
    width: fit-content;
    min-width: var(--treeWidth);
  }
  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px ;
    font-size: 20px;
    background-size: 100% 100%;
  }
}

</style>
